#pragma once
#include <iostream>
#include <string>
#include <sys/types.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <netinet/in.h>
#include <cstring>
#include <functional>

enum error
{
    SOCK_ERROR = 2,
    BIND_ERROR,
    SENDTO_ERROR
};

class udp_client
{
public:
    udp_client(const std::string &serve_ip, const uint16_t &serve_port)
        : _sockfd(-1), _serve_ip(serve_ip), _serve_port(serve_port) {}

    void init()
    {
        _sockfd = socket(AF_INET, SOCK_DGRAM, 0);
        if (_sockfd == -1)
        {
            std::cerr << "socket:" << errno << ":" << strerror(errno) << std::endl;
            exit(SOCK_ERROR);
        }
        // 客户端由系统自动绑定端口,不必手动绑定ip,端口
    }

    void start()
    {
        while (1)
        {
            std::string buffer;
            std::cout << "请输入# ";
            getline(std::cin, buffer);
            // getline(std::cin, buffer);

            struct sockaddr_in serve;
            serve.sin_family = AF_INET;
            serve.sin_port = htons(_serve_port);
            serve.sin_addr.s_addr = inet_addr(_serve_ip.c_str());

            int ret = sendto(_sockfd, buffer.c_str(), buffer.size(), 0, (sockaddr *)&serve, sizeof(sockaddr_in));
            if (ret == -1)
            {
                std::cerr << "sendto:" << errno << ":" << strerror(errno) << std::endl;
                exit(SENDTO_ERROR);
            }
            char result[255];
            socklen_t sockaddr_in_size;
            int size = recvfrom(_sockfd, &result, sizeof(result), 0, (sockaddr*)&serve, &sockaddr_in_size);
            result[size] = 0;
            std::cout << "翻译结果#" << result << std::endl;
        }
    }

    ~udp_client()
    {
    }

private:
    int _sockfd;
    std::string _serve_ip;
    uint16_t _serve_port;

};